package com.pkg;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import java.security.Key;
import java.security.KeyFactory;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.UUID;


/**
 * <p>打包时请注意添加混淆
 * <p>打包时请注意添加混淆
 * <p>打包时请注意添加混淆
 */
public abstract class Codec {

    /**
     * 返回对方的公钥
     *
     * @return
     */
    protected abstract String getPublicKey();

    /**
     * 返回自己的私钥
     *
     * @return
     */
    protected abstract String getPrivateKey();

    protected String getEncode() {
        return "UTF-8";
    }

    protected String generatorKey() {
        return UUID.randomUUID().toString().replaceAll("[-]", "");
    }

    protected String byteArr2HexStr(byte[] arrB) throws Exception {
        int iLen = arrB.length;
        StringBuffer sb = new StringBuffer(iLen * 2);
        for (int i = 0; i < iLen; i++) {
            int intTmp = arrB[i];
            while (intTmp < 0) {
                intTmp = intTmp + 256;
            }
            if (intTmp < 16) {
                sb.append("0");
            }
            sb.append(Integer.toString(intTmp, 16));
        }
        return sb.toString();
    }

    protected byte[] hexStr2ByteArr(String strIn) throws Exception {
        byte[] arrB = strIn.getBytes(getEncode());
        int iLen = arrB.length;

        byte[] arrOut = new byte[iLen / 2];
        for (int i = 0; i < iLen; i = i + 2) {
            String strTmp = new String(arrB, i, 2);
            arrOut[i / 2] = (byte) Integer.parseInt(strTmp, 16);
        }
        return arrOut;
    }

    /**
     * 将str字符串加密，并将结果按json格式返回
     *
     * @param str
     * @return
     */
    public Map<String, String> encode(String str) {
        //生成随机密钥KEY  (UUID)
        String key = generatorKey();

        DES des = new DES();
        RSA rsa = new RSA();
        try {
            byte[] bs = rsa.encryptByPublicKey(key.getBytes(getEncode()), getPublicKey());

            String encodedKey = byteArr2HexStr(bs);

            String encodedValue = byteArr2HexStr(des.encrypt(str.getBytes(getEncode()), key));

            Map<String, String> map = new HashMap<String, String>();
            map.put("a", encodedKey);
            map.put("b", encodedValue);

            return map;
        } catch (Exception e) {
            throw new RuntimeException("encode fail",e);
        }
    }

    /**
     * 将json格式加密字符串解密为加密前状态
     *
     * @return
     * @Param
     */
    public String decode(String a, String b) {
        DES des = new DES();
        RSA rsa = new RSA();

        try {
            String encodedKey = byteArr2HexStr(rsa.decryptByPrivateKey(hexStr2ByteArr(a), getPrivateKey()));

            encodedKey = new String(hexStr2ByteArr(encodedKey), getEncode());

            String encodedValue = new String(des.decrypt(hexStr2ByteArr(b), encodedKey), getEncode());

            return encodedValue;
        } catch (Exception e) {
            throw new RuntimeException("decode fail",e);
        }

    }

    protected byte[] decryptBASE64(String key) throws Exception {
        return (new BASE64Decoder()).decodeBuffer(key);
    }

    protected String encryptBASE64(byte[] key) throws Exception {
        return (new BASE64Encoder()).encodeBuffer(key);
    }

    class RSA {
        byte[] encryptByPublicKey(byte[] data, String key) throws Exception {
            byte[] keyBytes = decryptBASE64(key);
            X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(keyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            Key publicKey = keyFactory.generatePublic(x509EncodedKeySpec);

            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);

            cipher.update(data);
            return cipher.doFinal();
        }

        byte[] decryptByPrivateKey(byte[] data, String key) throws Exception {
            byte[] keyBytes = decryptBASE64(key);

            PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(keyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            Key privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);

            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
            cipher.init(Cipher.DECRYPT_MODE, privateKey);

            cipher.update(data);
            return cipher.doFinal();
        }
    }

    class DES {

        public byte[] encrypt(byte[] data, String key) throws Exception {
            Cipher cipher = Cipher.getInstance("DES");
            Key jkey = getKey(key.getBytes(Codec.this.getEncode()));
            cipher.init(Cipher.ENCRYPT_MODE, jkey);
            cipher.update(data);
            return cipher.doFinal();
        }

        public byte[] decrypt(byte[] data, String key) throws Exception {
            Cipher cipher = Cipher.getInstance("DES");
            Key jkey = getKey(key.getBytes(Codec.this.getEncode()));
            cipher.init(Cipher.DECRYPT_MODE, jkey);
            cipher.update(data);
            return cipher.doFinal();

        }

        private Key getKey(byte[] arrBTmp) throws Exception {
            byte[] arrB = new byte[8];

            for (int i = 0; i < arrBTmp.length && i < arrB.length; i++) {
                arrB[i] = arrBTmp[i];
            }

            Key key = new javax.crypto.spec.SecretKeySpec(arrB, "DES");

            return key;
        }

    }


    protected static int len = 8;

    /**
     * 字节增加随机前8位
     * @param bytes
     * @return
     */
    public static byte[] byteEncode(byte[] bytes) {
        if (null != bytes) {
            byte[] bs = new byte[bytes.length + len];
            byte[] tmpbs = new byte[len];
            new Random().nextBytes(tmpbs);
            System.arraycopy(tmpbs, 0, bs, 0, len);
            System.arraycopy(bytes, 0, bs, len, bytes.length);
            return bs;
        }
        return null;
    }

    /**
     * 删去前8位字节
     * @param bytes
     * @return
     */
    public static byte[] byteDecode(byte[] bytes) {
        if (null != bytes && bytes.length >= len) {
            byte[] bs = new byte[bytes.length - len];
            System.arraycopy(bytes, len, bs, 0, bytes.length - len);
            return bs;
        }
        return null;
    }

}
